<?php
/**
 * 原点 2020年7月14日17:47:36 商品相关
 * getProduct() => 获取商品
 * read() => 商品详情
 * submit() => 提交订单
 */

namespace app\index\model;

use app\common\lib\Redis;
use think\Db;
use think\Model;
class Goods extends Model
{
    protected $name = 'goods';

    public static function getProduct($where, $page, $limit, $field, $order)
    {
        try {
            $where['is_del'] = 0;
            $where['is_enable'] = 1;

            return self::all(function ($query) use ($where, $page, $limit, $field, $order) {
                $query->where($where)->field($field)->page($page, $limit)->order($order);
            });

        } catch (\Exception $e) {

            return [];
        }
    }
    public function read($id, $user = [])
    {
        try {
            $where = ['is_del' => 0, 'is_enable' => 1, 'id' => $id];
            $list = $this->get($where);
            $list['images'] = db('product_image')->where('upid', $id)->select();
//            if ($list['category1'] == 2) {
//                $list['group_price'] = db('group_cate')->where('id', $list['group_cate_id'])->value('price');
//            }
            $list['evaluate'] = Evaluate::all(function ($query) use ($list) {
                $query->alias('e')
                    ->join('member m', 'e.uid = m.id')
                    ->where('find_in_set(' . $list['id'] . ',product_id)')
                    ->field('e.*,m.nickname,m.photo')
                    ->order('create_time desc');
            });
            if ($user) {
                $res=Redis::Instance()->sAdd('tracks_' . $user['code'], $id);
            }
            $is_collect = db('member_collect')->where(['code' => $user['code'], 'product_id' => $id])->find();
            $cart = Cart::where('uid', $user['id'])->sum('num');

            $list['cart_count'] = $cart ? $cart : 0;
            if ($is_collect) {
                $list['is_collect'] = 1;
            } else {
                $list['is_collect'] = 0;
            }
            return $list;

        } catch (\Exception $e) {
            return [];
        }
    }

    public function submit($param, $user)
    {
        try {

            if (!request()->isPost()) {
                return json(['code' => -5, 'msg' => '请求拒绝']);
            }
            $info = $this->get($param['id']);
            if (empty($info)) {
                return json(['code' => -1, 'msg' => '商品不存在或已下架']);
            }
            // if ($user['level_id'] ==1 && $info['category1'] > 1) {
            //     return json(['code' => -1, 'msg' => '请先在拼商区消费']);
            // }
            if (!$param['num'] || $param['num'] <= 0) {
                return json(['code' => -1, 'msg' => '数量错误']);
            }

            //暂存redis,方便存取
            $all[0]['id'] = $param['id'];
            $all[0]['num'] = $param['num'];
            if ($info['category1'] == 1) {
//             //查询时间
              /*  $cate = Db::name('product_cate')->where('id', $info['category2'])->find();
               $his = date('H:i:s');
               if ($his >= '12:00:00' && $his < '19:00:00') {
                   $os = explode(' - ', $cate['afternoon']);
               } else if($his >= '19:00:00'){
                   $os = explode(' - ', $cate['night']);
               }else{
                   $os = explode(' - ', $cate['morning']);
               }
                if ($his < $os[0]|| $his > $os[1]) {
                   return json(['code' => -1, 'msg' => '拼团已结束']);
                }
                if ($param['num'] > 1) {
                    return json(['code' => -1, 'msg' => '拼团专区的商品只能单件下单']);
                }
                if (!$param['frequency']) {
                    return json(['code' => -1, 'msg' => '请选择拼团次数']);
                } 
                $buy_num=Redis::Instance()->hGet('u_buy_num'.$cate['id'],$user['id']);
                if($buy_num+$param['frequency']>10){
                    return json(['code' => -1, 'msg' => '还可拼团'.(10-$buy_num)]);
                }*/
                //查询今日参团数量
                $group=new Group();
                // $is = $group->getCount($user['id'], $param['id']);
                // if ($is >= config('group_day')) {
                //    return json(['code' => -1, 'msg' => '今日参加拼团次数已到达上限！']);
                // }
                // if($info['category1']==1){
                //     $is = $group->where(['uid' => $user['id'],'product_id'=>$info['id'],'state' => 1, 'pay_state' => 2])->find();
                //     if ($is) {
                //         return json(['code' => -1, 'msg' => '您已参团，请耐心等待开团！']);
                //     }
                    //拼团次数
                    // $g_num=db('member_level')->where('id',$user['level_id'])->value('num');
                    // if($param['num']>$g_num){
                    //     return json(['code' => -1, 'msg' => '一次可拼'.$g_num.'份']);
                    // }
                // }
                
            }
            // else if($info['category1']==3){
            //     $arr=explode(',',config('seckill_time'));
            //     $time=[
            //         'start'=>strtotime($arr['0']),
            //         'end'=>strtotime($arr['1'])
            //     ];
            //     if(time()<$time['start']||time()>$time['end']){
            //        return json(['code' => -1, 'msg' => '秒杀已结束']);
            //     }
            // }else{
            //     if($user['level_id']==1){
            //         return json(['code' => -1, 'msg' => '请先在拼商区消费']);
            //     }
            // }
            if ($info['category1'] == 1 && $param['num'] > 1) {
                return json(['code' => -1, 'msg' => '拼团专区商品只能单件下单']);
            }
            $all['category1'] = $info['category1'];
            $all['category2'] = $info['category2'];
            Redis::Instance()->hSet('order', $user['code'], json_encode($all));
            return json(['code' => 1, 'msg' => 'success']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

    public function test_time($sum, $time)
    {

        if ($time >= $sum[0] && $time <= $sum[1]) {
            return true;
        } else {
            return false;
        }
    }

    public function collect($param, $user)
    {
        try {
            if (!$user) {
                return json(['code' => -3, 'msg' => '未登录']);
            }
            $common = db('member_collect');
            if ($param['type'] == 1) {
                db('member_collect')->insert([
                    'uid' => $user['id'],
                    'code' => $user['code'],
                    'product_id' => $param['id'],
                    'create_time' => time()
                ]);
            } else if ($param['type'] == 3) {
                $common->where(['uid' => $user['id']])->delete();
            } else {
                $common->where(['uid' => $user['id'], 'product_id' => $param['id']])->delete();
            }
            return json(['code' => 1, 'msg' => 'success']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

    public function get_tracks($code, $page)
    {
        try {
            $list = Redis::Instance()->sMembers('tracks_' . $code);
            $start = ($page - 1) * 10;
            $list = array_slice($list, $start, 10);
            foreach ($list as &$v) {
                $v = $this->where('id', $v)->field('id,title,image,retail_price')->find();
            }
            return $list;
        } catch (\Exception $e) {
            return false;
        }
    }

    public function clear_tracks($param, $code)
    {
        try {
            if ($param['type'] == 1) {
                Redis::Instance()->sRem('tracks_' . $code, $param['id']);
            } else {
                Redis::Instance()->del('tracks_' . $code);
            }

            return json(['code' => 1, 'msg' => '已删除']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

}
